﻿CREATE PROCEDURE [dbo].[smenu_TrackerRequest_Send]
(	@TrackerRequestID int,--TrackerRequestID
	@Dir int, -- 1 - Next, -1 - Previous, 0 - Anywhere, NULL - is not supported
	@System bit -- 1 - use System, 0 - use UserGroups(), NULL - check is Technician is SysTech
)
AS
IF @@ERROR <> 0 RETURN

SET NOCOUNT ON

DECLARE @StatusID int

IF @System IS NULL
	SELECT @System = COUNT(*) FROM  t_TrackerRequest WHERE ID = @TrackerRequestID AND TechnicianID = -1

EXEC sh_Debug_Print 'System:$0,@TrackerRequestID:$1',@System,@TrackerRequestID

IF @System = 1
	SELECT @StatusID = NextMenuID FROM fs_WorkFlow_System() wfs
	INNER JOIN t_TrackerRequest tr ON wfs.MenuID = tr.StatusID AND wfs.Direction = @Dir AND tr.ID = @TrackerRequestID 
ELSE SET @StatusID = dbo.NextRequestStatusByID(@TrackerRequestID, @Dir)

IF @StatusID IS NULL BEGIN
	DECLARE @Status sysname,@DirName sysname

	SELECT @Status = MenuName,@DirName = CASE @Dir WHEN 1 THEN 'Forward' ELSE 'Back' END
	FROM t_TrackerRequest tr INNER JOIN t_Menu m ON m.MenuID = tr.StatusID
	WHERE tr.ID = @TrackerRequestID

	IF @@TRANCOUNT > 0 ROLLBACK TRAN
	RAISERROR('<B>There is no path [%s] from [%s].</B>
',16,1,@DirName,@Status)
	RETURN
END

DECLARE @CI int EXEC @CI = sp__Context_WorkFlow_System @System
UPDATE t_TrackerRequest SET StatusID = @StatusID WHERE ID = @TrackerRequestID

IF @@ERROR <> 0 BEGIN
	IF @@TRANCOUNT > 0 ROLLBACK TRAN
	RETURN
END

EXEC sp__Context @CI





